package controller;

import com.google.gson.Gson;
import entry.Enterprise;
import entry.Instituty;
import entry.Ticket_open;
import pojo.XianShi;
import service.EnterpriseService;
import service.InstitutyService;
import service.Ticket_openService;
import service.impl.EnterpriseServiceImpl;
import service.impl.InstitutyServiceImpl;
import service.impl.Ticket_openServiceImpl;

import util.Page;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.UUID;

import static utils.PojoUtils.pojo;
@SuppressWarnings("all")
@WebServlet("/Ticket_openServlet/*")
public class Ticket_openServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //0、处理乱码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        //1.获得请求路径
        String url = request.getRequestURI();
        String methodName = url.substring(url.lastIndexOf("/") + 1);
        Class cla = Ticket_openServlet.class;
        try {
            Method method = cla.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(cla.newInstance(), request, response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public void openList(HttpServletRequest request, HttpServletResponse response) {
        String no = request.getParameter("no");
        String acquire_enterprise_id = request.getParameter("acquire_enterprise_id");
        String enterprise_id = request.getParameter("enterprise_id");
        String create_time = request.getParameter("create_time");
        String status = request.getParameter("status");
        String amountmin = request.getParameter("amountmin");
        String amountmax = request.getParameter("amountmax");
    }

    public void addTickOpen(HttpServletRequest request, HttpServletResponse response) {
        String acquire_enterprise_name = request.getParameter("acquire_enterprise_name");
        String enterprise_name = request.getParameter("enterprise_name");
        String amount = request.getParameter("amount");
        String instituty_name = request.getParameter("instituty_name");
        String create_time = request.getParameter("create_time");
        String expiry_time = request.getParameter("expiry_time");
        String payment_interest_type = request.getParameter("payment_interest_type");
        String beizhu = request.getParameter("beizhu");

        System.out.println(acquire_enterprise_name+"////"+enterprise_name+"////"+amount+"////"+instituty_name+"////"+create_time+"////"+expiry_time+"////"+payment_interest_type+"////"+beizhu);
        EnterpriseService enterpriseService = new EnterpriseServiceImpl();
        //通过收单企业名称查收单企业id
        Enterprise s = enterpriseService.selectEIdByName(acquire_enterprise_name);

        //通过开单企业名称查开单企业id
        Enterprise d = enterpriseService.selectEIdByName(enterprise_name);


        //通过金融机构名称查金融机构id
        InstitutyService institutyService = new InstitutyServiceImpl();
        Instituty instituty = institutyService.selectIdByName(instituty_name);
        Ticket_open ticket_open1 = new Ticket_open();

        VoucherNumberGenerator voucherNumberGenerator = new VoucherNumberGenerator();

        ticket_open1.setNo(voucherNumberGenerator.generateVoucherNumber());

        ticket_open1.setEnterprise_id(d.getId());
        ticket_open1.setAcquire_enterprise_id(s.getId());
        ticket_open1.setAmount(Double.parseDouble(amount));
        ticket_open1.setInstituty_id(instituty.getInstituty_id());
        ticket_open1.setCreate_time(create_time);
        ticket_open1.setExpiry_time(expiry_time);
        ticket_open1.setPayment_interest_type(payment_interest_type);
        ticket_open1.setStatus("开单中");
        ticket_open1.setUplink_address(UUID.randomUUID().toString().substring(19));
        Ticket_openService ticket_openService = new Ticket_openServiceImpl();
        ticket_openService.insertTicket_open(ticket_open1);

//        ticket_open.setAcquire_enterprise_id();
    }

    public static class VoucherNumberGenerator {
        Ticket_openService ticket_openService = new Ticket_openServiceImpl();
        Ticket_open ticket_open = new Ticket_open();

        private static int sequence = 1;
        private static final int SEQUENCE_LENGTH = 6;
        Page page = new Page();
        XianShi xianShi = new XianShi();
        public String generateVoucherNumber() {

            ArrayList<Ticket_open> tic = ticket_openService.queryAll(page,xianShi);
            int x = tic.size();
            Ticket_open x1 = tic.get(x-1);
            String w = x1.getNo();
            sequence = Integer.parseInt(w.substring(10))+1;
            // 获取当前日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String date = sdf.format(new Date());

            // 生成序列号并补齐到6位
            String sequenceStr = String.format("%0" + SEQUENCE_LENGTH + "d", sequence);

            // 生成凭证编号
            return "N" + date + sequenceStr;
        }
    }


    public void queryAllList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        XianShi xianShi1 = new XianShi();
        Page page = new Page();
        Ticket_openService ticket_openService = new Ticket_openServiceImpl();
        EnterpriseService enterpriseService = new EnterpriseServiceImpl();
        ArrayList<Ticket_open> list = ticket_openService.queryAll(page,xianShi1);
        InstitutyService institutyService = new InstitutyServiceImpl();
        ArrayList<XianShi> xianShi = new ArrayList<>(list.size());
        for (int i = 0; i < list.size(); i++) {
            XianShi xianShiItem = new XianShi();
            Instituty instName = institutyService.selectNameById(list.get(i).getInstituty_id());
            Enterprise topen = enterpriseService.selectNameById(list.get(i).getEnterprise_id());
            Enterprise acquTopen1 = enterpriseService.selectNameById(list.get(i).getAcquire_enterprise_id());

            xianShiItem.setNo(list.get(i).getNo());
            xianShiItem.setAmount(list.get(i).getAmount());
            xianShiItem.setKaidanTime(list.get(i).getCreate_time());
            xianShiItem.setStatus(list.get(i).getStatus());
            xianShiItem.setShangLian(list.get(i).getUplink_address());
            xianShiItem.setShouDanTime(list.get(i).getExpiry_time());
            xianShiItem.setInstituName(instName.getName());
            xianShiItem.setKaiDanName(topen.getName());
            xianShiItem.setShouDanName(acquTopen1.getName());
            if (list.get(i).getStatus().equals("开单中")) {
                xianShiItem.setOperate("<a>详情</a>&nbsp<a>撤销</a>");
            }

            xianShi.add(xianShiItem);
        }
        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(xianShi));
    }


    //    static int nun = 1;
    public void fenYe(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int pageIndex = Integer.parseInt(request.getParameter("pageIndex")); // 当前页码
        int pageSize = 3; // 每页显示条数
        XianShi xianShi = new XianShi();
        Page page = new Page();
        page.setPageIndex(pageIndex);
        page.setPageSize(pageSize);
        Ticket_openService ticket_openService = new Ticket_openServiceImpl();
        ArrayList<Ticket_open> list = ticket_openService.queryAll(page,xianShi);
        long totalItems = ticket_openService.selectBookSize();
        page.setTotalItems(totalItems);
        page.setItems(pojo(list));
        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(page));
    }




    public void shijian(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 获取当前日期
        Date currentDate = new Date();

        // 创建日期格式化对象
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        // 将当前日期格式化为字符串
        String formattedDate = sdf.format(currentDate);

        // 输出格式化的日期
        System.out.println("Current date: " + formattedDate);

        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(formattedDate));
    }

    public void cheXiao(HttpServletRequest request, HttpServletResponse response){
        String no = request.getParameter("no");
        Ticket_openService ticket_openService = new Ticket_openServiceImpl();
        Ticket_open ticket_open = new Ticket_open();
        ticket_open.setStatus("已撤销");
        ticket_open.setNo(no);
        boolean b = ticket_openService.updateTicket_open(ticket_open);
        System.out.println(b);
    }


    public void moHuChaXun1(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String no = request.getParameter("value");                         //获取当前模糊查询的no编号值
        String shouDanName = request.getParameter("shouDanName");              //获取当前模糊查询需要的收单公司的名字
        String KaiDanName = request.getParameter("KaiDanName");               //获取当前模糊查询需要的开单公司的名字
        int pageIndex = Integer.parseInt(request.getParameter("currentPage"));  //获得当前是第几页代码
        System.out.println(no+"++++"+shouDanName+"++++++"+KaiDanName+"++++++"+pageIndex);
        int pageSize = 3;                                                         // 每页显示条数
        XianShi xianShi = new XianShi();                                               //创建一个pojo对象，方便后期显示数据
        EnterpriseService enterpriseService = new EnterpriseServiceImpl();    //创建一个企业方法的服务层
        Enterprise kaiDanenterprise1;                                                   //创建一个企业对象
        if (!KaiDanName.equals("")) {
            kaiDanenterprise1 = enterpriseService.selectEIdByName(KaiDanName);        //通过企业id获取企业name
        } else {
            kaiDanenterprise1 = null;
        }

        Enterprise shouDanenterprise;
        if (!shouDanName.equals("")) {
            shouDanenterprise = enterpriseService.selectEIdByName(shouDanName);       //通过企业id获取企业name
        } else {
            shouDanenterprise = null;
        }

        if (!no.equals("")){
            xianShi.setNo(no);                                                      //将当前模糊查询编号的数据放入no
        }

        if (kaiDanenterprise1 != null) {
            xianShi.setKaiDnaId(kaiDanenterprise1.getId());                         //将id放入pojo帮助实体类
        }

        if (shouDanenterprise != null) {
            xianShi.setShouDanId(shouDanenterprise.getId());                        //将id放入pojo帮助实体类
        }

        Page page = new Page();
        page.setPageIndex(pageIndex);
        page.setPageSize(pageSize);
        Ticket_openService ticket_openService = new Ticket_openServiceImpl();
        ArrayList<Ticket_open> list = ticket_openService.queryAll(page, xianShi);
        long totalItems = ticket_openService.selectBookSize();
        page.setTotalItems(totalItems);
        page.setItems(pojo(list));

        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(page));
    }

    public void moHuChaXun(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String no = request.getParameter("value1");                         //获取当前模糊查询的no编号值
        String shouDanName = request.getParameter("shouDanName");              //获取当前模糊查询需要的收单公司的名字
        String kaiDanName = request.getParameter("KaiDanName");               //获取当前模糊查询需要的开单公司的名字
        int pageIndex = Integer.parseInt(request.getParameter("pageIndex"));  //获得当前是第几页代码
        int pageSize = 3;                                                         // 每页显示条数
        XianShi xianShi = new XianShi();                                               //创建一个pojo对象，方便后期显示数据
        EnterpriseService enterpriseService = new EnterpriseServiceImpl();    //创建一个企业方法的服务层
        if(kaiDanName != null && kaiDanName.length() > 0){
            Enterprise enterprise = enterpriseService.selectEIdByName(kaiDanName);
            if(enterprise != null){
                xianShi.setKaiDnaId(enterprise.getId());
            }
        }
        if (shouDanName != null && shouDanName.length() > 0) {
            Enterprise enterprise = enterpriseService.selectEIdByName(shouDanName);       //通过企业id获取企业name
            if(enterprise != null){
                xianShi.setShouDanId(enterprise.getId());
            }
        }
        if (no != null && no.length() > 0) {
            xianShi.setNo(no);                                                      //将当前模糊查询编号的数据放入no
        }
        Page page = new Page();
        page.setPageIndex(pageIndex);
        page.setPageSize(pageSize);
        Ticket_openService ticket_openService = new Ticket_openServiceImpl();
        page = ticket_openService.queryAllPage(page, xianShi);
        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(page));
    }

    public void moHuChaXun12(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String no = request.getParameter("value1");                         //获取当前模糊查询的no编号值
        String shouDanName = request.getParameter("shouDanName");              //获取当前模糊查询需要的收单公司的名字
        String kaiDanName = request.getParameter("KaiDanName");               //获取当前模糊查询需要的开单公司的名字
        int pageIndex = Integer.parseInt(request.getParameter("pageIndex"));  //获得当前是第几页代码
        int pageSize = 3;                                                         // 每页显示条数
        XianShi xianShi = new XianShi();                                               //创建一个pojo对象，方便后期显示数据
        EnterpriseService enterpriseService = new EnterpriseServiceImpl();    //创建一个企业方法的服务层
        if(kaiDanName != null && kaiDanName.length() > 0){
            Enterprise enterprise = enterpriseService.selectEIdByName(kaiDanName);
            if(enterprise != null){
                xianShi.setKaiDnaId(enterprise.getId());
            }
        }
        if (shouDanName != null && shouDanName.length() > 0) {
            Enterprise enterprise = enterpriseService.selectEIdByName(shouDanName);       //通过企业id获取企业name
            if(enterprise != null){
                xianShi.setShouDanId(enterprise.getId());
            }
        }
        if (no != null && no.length() > 0) {
            xianShi.setNo(no);                                                      //将当前模糊查询编号的数据放入no
        }
        Page page = new Page();
        page.setPageIndex(pageIndex);
        page.setPageSize(pageSize);
        Ticket_openService ticket_openService = new Ticket_openServiceImpl();
        page = ticket_openService.queryAllPage1(page, xianShi);
        Gson gson = new Gson();
        response.getWriter().println(gson.toJson(page));
    }

}
